// ignore_for_file: deprecated_member_use_from_same_package

import 'package:dartkit/dartkit.dart';
import 'package:test/test.dart';

// 用于测试的各种数据
final _date = Date.now();

Future<Diary> createDiary(Date date, {int userId = idTest}) =>
    diaryTable.create({"date": date, "user_id": userId});

void main() {
  /// 创建一个独立的数据库
  prepareAndCleanPostgres("diaries_test_db");

  test("增加日记实验", () async {
    // 创建一条新日记，预期所有内容都匹配
    final diary = await createDiary(_date);
    expect(diary.content, "");
    expect(diary.title, "");
    expect(diary.date, _date);
    expect(diary.id, 1);
  });

  test("寻找日记实验", () async {
    // 在今天和昨天创建2条日记，又给别人创建一条日记
    await createDiary(_date);
    await createDiary((_date - 1));
    // 创建新用户后，用id2添加日记
    await userTable.create({"phone": "15900782115"});
    await createDiary(_date, userId: 2);
    // 最终根据id查找，能找到2条日记
    List<Diary> founds = await diaryTable.findFor(idTest);
    expect(founds, hasLength(2));
  });

  test("寻找单个日记实验", () async {
    // 原来根据id1查找无法找到
    final Diary? foundBefore = await diaryTable.find(1);
    expect(foundBefore, isNull);

    // 创建一个日记，然后通过id1查找，能找到
    await createDiary(_date);
    final Diary? foundAfter = await diaryTable.find(1);
    expect(foundAfter, isNotNull);
  });

  test("重复添加实验", () async {
    // 将相同日期和用户的日记添加2次，第二次会有报错
    await createDiary(_date);
    expect(() async => await createDiary(_date), isPostgresBug);
  });

  test("更新日记实验", () async {
    // 添加一个日记，修改后更新
    final diary = await createDiary(_date);
    diary.title = "title";
    diary.content = "content";
    await diaryTable.update(diary);
    // 查找日记，发现和修改后的内容一致
    final Diary? found = await diaryTable.find(diary.id);
    expect(found?.title, "title");
    expect(found?.content, "content");
  });

  test("更新不存在的日记", () async {
    // 更新一个不存在的日记会报错
    final diary =
        Diary(id: idTest, date: _date, title: "测试日记", content: "测试日记的内容");
    expect(() async => await diaryTable.update(diary), isBug);
  });

  test("删除日记", () async {
    // 创建一个番茄，然后删除它
    final diary = await createDiary(_date);
    await diaryTable.delete(diary.id);
    // 发现无法找到这个番茄
    final Diary? found = await diaryTable.find(diary.id);
    expect(found, isNull);
    // 但如果重复删除，则会报错
    expect(() async => await diaryTable.delete(diary.id), isBug);
  });
}
